package com.example.mrweather;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import android.Manifest;
import android.content.pm.PackageManager;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.TransitionDrawable;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationServices;
import com.squareup.picasso.Picasso;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class MainActivity extends AppCompatActivity {

    private static final int LOCATION_PERMISSION_REQUEST_CODE = 100;
    private FusedLocationProviderClient fusedLocationClient;
    private TextView tvLocation, tvTemperature, tvWeatherDescription, tvHumidity, tvWindSpeed, tvPressure;
    private ImageView ivWeatherIcon;
    private SwipeRefreshLayout swipeRefreshLayout;
    private LinearLayout forecastContainer;

    // 使用OpenWeatherMap API
    private final String API_KEY = "YOUR_API_KEY"; // 替换为您的实际API密钥
    private final String BASE_URL = "https://api.openweathermap.org/data/2.5/";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // 初始化视图
        initViews();

        // 初始化位置服务
        fusedLocationClient = LocationServices.getFusedLocationProviderClient(this);

        // 设置下拉刷新监听器
        swipeRefreshLayout.setOnRefreshListener(() -> {
            getLocation();
            swipeRefreshLayout.setRefreshing(false);
        });

        // 首次加载时获取位置
        getLocation();
    }

    private void initViews() {
        tvLocation = findViewById(R.id.tvLocation);
        tvTemperature = findViewById(R.id.tvTemperature);
        tvWeatherDescription = findViewById(R.id.tvWeatherDescription);
        tvHumidity = findViewById(R.id.tvHumidity);
        tvWindSpeed = findViewById(R.id.tvWindSpeed);
        tvPressure = findViewById(R.id.tvPressure);
        ivWeatherIcon = findViewById(R.id.ivWeatherIcon);
        swipeRefreshLayout = findViewById(R.id.swipeRefreshLayout);
        forecastContainer = findViewById(R.id.forecastContainer);
    }

    private void getLocation() {
        // 检查位置权限
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
                != PackageManager.PERMISSION_GRANTED) {

            // 请求位置权限
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                    LOCATION_PERMISSION_REQUEST_CODE);
        } else {
            // 权限已授予，获取位置
            fetchLocation();
        }
    }

    private void fetchLocation() {
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
                != PackageManager.PERMISSION_GRANTED) {
            return;
        }

        fusedLocationClient.getLastLocation()
                .addOnSuccessListener(this, location -> {
                    if (location != null) {
                        // 获取当前天气
                        getWeatherData(location.getLatitude(), location.getLongitude());
                        // 获取天气预报
                        getForecastData(location.getLatitude(), location.getLongitude());
                    } else {
                        Toast.makeText(this, "无法获取位置信息", Toast.LENGTH_SHORT).show();
                    }
                });
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == LOCATION_PERMISSION_REQUEST_CODE) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                getLocation();
            } else {
                Toast.makeText(this, "需要位置权限", Toast.LENGTH_SHORT).show();
            }
        }
    }

    private void getWeatherData(double lat, double lon) {
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .build();

        WeatherApi api = retrofit.create(WeatherApi.class);
        Call<WeatherData> call = api.getWeatherByLocation(lat, lon, API_KEY, "metric");

        call.enqueue(new Callback<WeatherData>() {
            @Override
            public void onResponse(Call<WeatherData> call, Response<WeatherData> response) {
                if (response.isSuccessful() && response.body() != null) {
                    updateUI(response.body());
                } else {
                    Toast.makeText(MainActivity.this, "获取天气数据失败", Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Call<WeatherData> call, Throwable t) {
                Toast.makeText(MainActivity.this, "网络错误: " + t.getMessage(), Toast.LENGTH_SHORT).show();
            }
        });
    }

    private void getForecastData(double lat, double lon) {
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .build();

        WeatherApi api = retrofit.create(WeatherApi.class);
        // 获取5天预报（每3小时一条数据，5天共40条）
        Call<ForecastData> call = api.getWeatherForecast(lat, lon, API_KEY, "metric", 40);

        call.enqueue(new Callback<ForecastData>() {
            @Override
            public void onResponse(Call<ForecastData> call, Response<ForecastData> response) {
                if (response.isSuccessful() && response.body() != null) {
                    displayForecast(response.body());
                }
            }

            @Override
            public void onFailure(Call<ForecastData> call, Throwable t) {
                // 可以在这里处理错误，但为了简洁省略
            }
        });
    }

    private void updateUI(WeatherData weatherData) {
        tvLocation.setText(weatherData.getName());
        tvTemperature.setText(String.format("%.1f°C", weatherData.getMain().getTemp()));
        if (weatherData.getWeather() != null && weatherData.getWeather().length > 0) {
            String description = weatherData.getWeather()[0].getDescription();
            tvWeatherDescription.setText(description);

            String iconUrl = "https://openweathermap.org/img/wn/" +
                    weatherData.getWeather()[0].getIcon() + "@2x.png";
            Picasso.get().load(iconUrl).into(ivWeatherIcon);

            String weatherCondition = weatherData.getWeather()[0].getMain();
            updateBackground(weatherCondition);
        }

        tvHumidity.setText(String.format("%d%%", weatherData.getMain().getHumidity()));

        if (weatherData.getWind() != null) {
            double windSpeedKmh = weatherData.getWind().getSpeed() * 3.6;
            tvWindSpeed.setText(String.format("%.1f km/h", windSpeedKmh));
        }

        tvPressure.setText(String.format("%.0f hPa", weatherData.getMain().getPressure()));
    }
    private void updateBackground(String weatherCondition) {
        int backgroundResId;

        // 根据天气状况选择背景
        switch (weatherCondition.toLowerCase()) {
            case "clear":
                backgroundResId = R.drawable.bg_sunny;
                break;
            case "clouds":
                backgroundResId = R.drawable.bg_cloudy;
                break;
            case "rain":
            case "drizzle":
                backgroundResId = R.drawable.bg_rainy;
                break;
            case "thunderstorm":
                backgroundResId = R.drawable.bg_storm;
                break;
            default:
                backgroundResId = R.drawable.bg_default;
        }

        // 获取根视图
        View rootView = findViewById(android.R.id.content);

        // 获取当前背景
        Drawable currentBackground = rootView.getBackground();
        if (currentBackground == null) {
            currentBackground = ContextCompat.getDrawable(this, R.drawable.bg_default);
        }

        // 创建过渡动画
        TransitionDrawable transition = new TransitionDrawable(new Drawable[] {
                currentBackground,
                ContextCompat.getDrawable(this, backgroundResId)
        });

        // 设置新背景并启动动画
        rootView.setBackground(transition);
        transition.startTransition(1000); // 1秒过渡动画
    }

    private void displayForecast(ForecastData forecastData) {
        // 清除旧的预报视图
        forecastContainer.removeAllViews();

        // 设置日期格式
        SimpleDateFormat sdfDay = new SimpleDateFormat("E", Locale.getDefault());
        SimpleDateFormat sdfDate = new SimpleDateFormat("MMM d", Locale.getDefault());

        // 遍历预报数据
        List<ForecastData.ForecastItem> items = forecastData.getList();
        for (int i = 0; i < items.size(); i++) {
            ForecastData.ForecastItem item = items.get(i);
            Date date = new Date(item.getDt() * 1000);

            // 只显示中午12点的预报
            if (date.getHours() == 12) {
                // 创建预报项视图
                View forecastItem = getLayoutInflater().inflate(R.layout.item_forecast, forecastContainer, false);

                // 获取视图元素
                TextView tvDay = forecastItem.findViewById(R.id.tvForecastDay);
                TextView tvDate = forecastItem.findViewById(R.id.tvForecastDate);
                TextView tvTemp = forecastItem.findViewById(R.id.tvForecastTemp);
                ImageView ivIcon = forecastItem.findViewById(R.id.ivForecastIcon);

                // 设置数据
                tvDay.setText(sdfDay.format(date));
                tvDate.setText(sdfDate.format(date));
                tvTemp.setText(String.format("%.0f°", item.getMain().getTemp()));

                // 加载天气图标
                String iconUrl = "https://openweathermap.org/img/wn/" +
                        item.getWeather().get(0).getIcon() + ".png";
                Picasso.get().load(iconUrl).into(ivIcon);

                // 添加到容器
                forecastContainer.addView(forecastItem);
            }
        }
    }

    // 如果需要使用本地图标（替代网络图标）
    private void updateWeatherIcon(String iconCode, ImageView imageView) {
        int iconResId;

        // 根据图标代码选择本地图标资源
        switch (iconCode) {
            case "01d": // 晴天 (白天)
            case "01n": // 晴天 (夜晚)
                iconResId = R.drawable.ic_sunny;
                break;
            case "02d": // 少云 (白天)
            case "02n": // 少云 (夜晚)
                iconResId = R.drawable.ic_partly_cloudy;
                break;
            case "03d": // 多云 (白天)
            case "03n": // 多云 (夜晚)
            case "04d": // 阴天 (白天)
            case "04n": // 阴天 (夜晚)
                iconResId = R.drawable.ic_cloudy;
                break;
            case "09d": // 小雨 (白天)
            case "09n": // 小雨 (夜晚)
            case "10d": // 雨 (白天)
            case "10n": // 雨 (夜晚)
                iconResId = R.drawable.ic_rainy;
                break;
            case "11d": // 雷暴 (白天)
            case "11n": // 雷暴 (夜晚)
                iconResId = R.drawable.ic_storm;
                break;
            case "13d": // 雪 (白天)
            case "13n": // 雪 (夜晚)
                iconResId = R.drawable.ic_snow;
                break;
            default:
                iconResId = R.drawable.ic_unknown;
        }

        imageView.setImageResource(iconResId);
    }
}